package org.esjsoftware.v2m.rim.util;

import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.SIMCardException;
import net.rim.device.api.system.SIMCardInfo;

/**
 * 
 * @author Ernest
 *
 */
public class ServiceLocator {
	public static final int ONE_DAY = 24 * 60 * 60 * 1000;

	/**
	 * 
	 * @return String
	 */
	public static String getContactionString(){
		if(DeviceInfo.isSimulator()){
			return ";deviceside=true";
		}
		// Wifi is the preferred transmission method
		if(CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT, RadioInfo.WAF_WLAN, false)){
			return ";interface=wifi";
		}
//		if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
//			debugAndSave("Wifi coverage found");
//			return ";interface=wifi";
//		}
		// Is the carrier network the only way to connect?
		else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
			String carrierUid = getCarrierBIBSUid();
			if (carrierUid == null) {
				// Has carrier coverage, but not BIBS. So use the carrier's TCP
				// network
				return ";deviceside=true";
			} else {
				// otherwise, use the Uid to construct a valid carrier BIBS
				// request
				return ";deviceside=false;connectionUID=" + carrierUid
						+ ";ConnectionType=mds-public";
			}
		}
		// Check for an MDS connection instead (BlackBerry Enterprise Server)
		else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
			return ";deviceside=false";
		}
		// If there is no connection available abort to avoid bugging the user
		// unnecssarily.
		else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
			return "";
		}
		// In theory, all bases are covered so this shouldn't be reachable.
		else {
			return ";deviceside=true";
		}
	}
	
	/**
	 * 
	 * @return String
	 */
	private static String getCarrierBIBSUid() {
		ServiceRecord[] records = ServiceBook.getSB().getRecords();
		int currentRecord;

		for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
			if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
				if (records[currentRecord].getName().toLowerCase().indexOf(
						"bibs") >= 0) {
					return records[currentRecord].getUid();
				}
			}
		}

		return null;
	}
	
	/**
	 * 
	 * @return String
	 */
	public static String getIMSICode() {
		try {
			byte[] imsi = SIMCardInfo.getIMSI();
			String imsiCode = "";
			for (int i = 0; i < imsi.length; i++) {
				System.out.println(imsi[i]);
				imsiCode += String.valueOf(imsi[i]);
			}
			return imsiCode;
		} catch (SIMCardException e) {
			return "";
		}
	}
}
